<!-- 字段映射 -->
<template>
  <div class="w-full">
    <div
      v-show="rowDatas && rowDatas.length"
      class="grid gap-x-0 gap-y-0 grid-cols-4"
      :style="{ 'grid-template-columns': formMode?.mode === 'edit' ? '1fr  100px 1fr  60px' : ' 1fr 100px  1fr' }"
    >
      <!-- <div class="bg-fill-0 px-10 py-4 flex items-center">
        <mci-text model-value="数据集字段" />
      </div>
      <div class="bg-fill-0 px-10 py-4 flex items-center">
        <mci-text model-value="字段名称" />
      </div> -->
      <div class="pl-8 flex items-center">
        <!-- <mci-form-item label="决策流入参" prop="leftFields" /> -->
        <mci-text model-value="决策流入参" />
      </div>
      <div></div>
      <!-- <div class="bg-fill-0 px-10 py-4 flex items-center">
            <mci-text model-value="决策流参数" />
          </div>
          <div class="bg-fill-0 px-10 py-4 flex items-center">
            <mci-text model-value="参数名称" />
          </div> -->
      <div class="pl-8 flex items-center">
        <!-- <mci-form-item label="数据集字段" prop="rightFields" /> -->
        <mci-text model-value="数据集字段" />
      </div>
      <div v-if="formMode?.mode === 'edit'" class="bg-fill-0 px-10 flex items-center">
        <mci-text model-value="操作" />
      </div>
    </div>
    <div class="relative">
      <div
        v-for="(row, index) in rowDatas"
        :key="row.varName"
        class="grid gap-x-2 gap-y-4 mt-4"
        :style="{ 'grid-template-columns': formMode?.mode === 'edit' ? '1fr 100px 1fr 60px' : '1fr 100px 1fr' }"
      >
        <!-- <div class="px-10 py-4 flex items-center bg-fill-2">
            <mci-text :model-value="row.varName" />
          </div> -->
        <div class="pl-0 pb-4 flex items-center" :class="{ 'bg-fill-2': formMode?.mode !== 'edit' }">
          <!-- <mci-text :model-value="getVarLabel(row.varName)" class="w-full" /> -->
          <MciSelect v-model="row.targetVarName" :list="bussOptions" :disabled="true" class="w-full" size="default" />
        </div>
        <div class="flex items-center">
          <div
            v-if="index === 0"
            class="w-full"
          >
            <div
              class="absolute top-0 bottom-0"
              :style="{
                left: formMode?.mode === 'edit' ? 'calc(50% - 78px)' : 'calc(50% - 48px)',
                right: formMode?.mode === 'edit' ? 'calc(50% - 18px)' : 'calc(50% - 48px)'
              }"
            >
              <div class="flex items-center justify-center h-full w-full">
                <MciSvgIcon
                  :width="40"
                  :height="40"
                  :name="'mapping'"
                />
              </div>
            </div>
          </div>
          <div v-else class="w-full"></div>
        </div>
        <div class=" pb-4 flex items-center" :class="{ 'bg-fill-2': formMode?.mode !== 'edit' }">
          <!-- <mci-text :model-value="getTargetVarLabel(row.targetVarName)" /> -->
          <MciSelect v-model="row.varName" :list="allTableFieldOptions" :disabled="true" size="default" class="w-full" />
        </div>
        <div v-if="formMode?.mode === 'edit'" class="flex justify-center items-center bg-fill-2 my-4">
          <!-- <i v-show="formMode?.mode === 'edit'" class="mci-icon-close "  @click="handleDel(row.varName)"></i> -->
          <MciSvgIcon
            v-show="formMode?.mode === 'edit'"
            :width="18"
            :height="18"
            :name="'close'"
            class="cursor-pointer"
            @click="handleDel(row.varName)"
          />
        </div>
      </div>

      <!-- 新增行 -->
      <div
        v-show="formMode?.mode === 'edit' && addRowVisible"
        class="grid gap-x-2 gap-y-4 mt-4"
        :style="{ 'grid-template-columns': formMode?.mode === 'edit' ? '1fr 100px 1fr 60px' : '1fr 1fr 100px 1fr 1fr' }"
      >
        <div class="pl-0 py-4 flex items-center">
          <MciSelect
            v-model="addRow.targetVarName"
            :list="bussOptions"
            placeholder="请选择决策流参数"
            size="default"
            class="w-full"
            filterable
            @change="handleAddRowChange"
          />
        </div>
        <div></div>
        <div class="w-full py-4 flex items-center">
          <MciSelect
            v-model="addRow.varName"
            :list="tableFieldOptions"
            placeholder="请选择数据集字段"
            class="w-full"
            size="default"
            filterable
            @change="handleAddRowChange"
          />
        </div>
        <div class="flex justify-center items-center bg-fill-2 my-4">
          <!-- <i v-show="formMode?.mode === 'edit'" class="mci-icon-close" @click="handleDeleteAddRow()"></i> -->
          <MciSvgIcon
            :width="18"
            :height="18"
            :name="'close'"
            class="cursor-pointer"
            @click="handleDeleteAddRow()"
            @change="handleAddRowChange"
          />
        </div>
      </div>
    </div>
    <div v-show="formMode?.mode === 'edit'" class="flex items-center py-4">
      <mci-button type="default" :link="true" size="default" icon="mci-icon-add" @click="handleAdd()"> 添加字段 </mci-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue';
import { MciText, MciSelect, MciSvgIcon, MciButton, MciMessage } from '@/components/base';

const props = defineProps({
  columnOptions: {
    type: Array,
    default: () => []
  },
  variableOptions: {
    type: Array,
    default: () => []
  },
  isMatch: {
    type: Boolean,
    default: false
  },
  mapping: {
    type: Object,
    default: () => {}
  },
  disabled: {
    type: Boolean,
    default: false
  }
});
const emit = defineEmits(['change', 'match']);

// const formMode = useFormMode();
const formMode = { mode: props.disabled ? 'view' : 'edit' };

// 表字段
const tableFields = ref<any[]>([]);
// 业务字段
// const bussFields = ref<any[]>([]);
// 行数据
const rowDatas = ref<any[]>([]);
// 表字段选项
const tableFieldOptions = ref<any[]>([]);
const allTableFieldOptions = ref<any[]>([]);
// 业务字段选项
const bussOptions = ref<any[]>([]);
// 新增行
const addRow = reactive<any>({});
const addRowVisible = ref<boolean>(false);

const variableOptions = ref(props.variableOptions || []);
const resetAddRow = () => {
  addRow.varName = undefined;
  addRow.targetVarName = '';
};
resetAddRow();

watch(
  [() => props.columnOptions],
  () => {
    tableFields.value = props.columnOptions || [];
    buildOptions();
  },
  { deep: true }
);

watch(
  [() => props.variableOptions],
  () => {
    variableOptions.value = props.variableOptions || [];
    buildOptions();
  },
  { deep: true }
);

watch([() => props.disabled], () => {
  formMode.mode = props.disabled ? 'view' : 'edit';
});

// 构造选项
const buildOptions = () => {
  if (tableFields.value) {
    tableFieldOptions.value = tableFields.value
      .filter((item1) => !rowDatas.value.some((item2) => item1.varName === item2.varName))
      ?.map((item) => {
        return {
          label: item.varLabel,
          value: item.varName
        };
      });
    allTableFieldOptions.value = tableFields.value?.map((item) => {
      return {
        label: item.varLabel,
        value: item.varName
      };
    });
  } else {
    tableFieldOptions.value = [];
    allTableFieldOptions.value = [];
  }

  if (variableOptions.value) {
    // bussOptions.value = variableOptions.value.filter(
    //   (item1) => !rowDatas.value.some((item2) => item1.value === item2.targetVarName)
    // );
    bussOptions.value = [...variableOptions.value];
  } else {
    bussOptions.value = [];
  }
};

// 同名匹配
const nameMatch = () => {
  tableFieldOptions.value.forEach((item1) => {
    if (bussOptions.value.some((item2) => item1.value === item2.value)) {
      // 添加数据
      const newrow = {
        varName: item1.value,
        targetVarName: item1.value
      };
      rowDatas.value.push(newrow);
    }
  });
  emit('change', buildMapping());
  emit('match');
};

// 添加
const handleCheck = () => {
  if (addRow.varName && addRow.targetVarName) {
    // 添加数据
    const newrow = {
      varName: addRow.varName,
      targetVarName: addRow.targetVarName
    };
    rowDatas.value.push(newrow);
    emit('change', buildMapping());
    // 更新选项
    buildOptions();
    addRow.varName = '';
    addRow.targetVarName = '';
  } else {
    MciMessage({
      message: '请选择字段',
      type: 'warning'
    });
  }
};

// 删除添加行
const handleDeleteAddRow = () => {
  addRowVisible.value = false;
};

// 添加行
const handleAdd = () => {
  if (addRowVisible.value) {
    if (addRow.varName && addRow.targetVarName) {
      handleCheck();
      // 添加编辑行
      resetAddRow();
    } else {
      MciMessage({
        message: '请选择字段后，再尝试该操作',
        type: 'warning'
      });
    }
  } else {
    addRowVisible.value = true;
    resetAddRow();
  }
};

// 移除行
const handleDel = (varName: any) => {
  if (varName) {
    const index = rowDatas.value.findIndex((item) => item.varName === varName);
    if (index > -1) {
      rowDatas.value.splice(index, 1);
      buildOptions();
      emit('change', buildMapping());
    }
  }
};

// 清除
const clear = () => {
  rowDatas.value = [];
  resetAddRow();
};

// 数据转化
const buildMapping = () => {
  const mapping: any = {};
  for (const rowData of rowDatas.value) {
    mapping[rowData.varName] = rowData.targetVarName;
  }
  if (addRow && addRow.varName && addRow.targetVarName) {
    mapping[addRow.varName] = addRow.targetVarName;
  }
  return mapping;
};

const handleAddRowChange = () => {
  emit('change', buildMapping());
};

// 数据转化
const buildRowData = (mapping: any) => {
  clear();
  if (mapping) {
    const keys = Object.keys(mapping) || [];
    const arr = keys.map((key) => {
      return {
        varName: key,
        targetVarName: mapping[key]
      };
    });
    rowDatas.value = arr;
  } else {
    rowDatas.value = [];
  }
  buildOptions();
};
buildRowData(props.mapping);

// if (formMode?.mode === 'edit' && (!rowDatas.value || rowDatas.value.length === 0)) {
//   handleAdd();
// }

// 显示名称
// const getVarLabel = (name: string) => {
//   return tableFields.value?.find((item) => item.varName === name)?.varLabel;
// };
// const getTargetVarLabel = (name: string) => {
//   return variableOptions.value?.find((item: any) => item.value === name)?.label;
// };
defineExpose({
  buildRowData
});
</script>

<style lang="scss" scoped></style>
